package com.woniuxy.credit_loans.product_liu.controller;

import com.woniuxy.credit_loans.util.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class BaseLController {
    @PostMapping("/uploadLJ")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String path = request.getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
            System.out.println(path);
        }

        String originalFileName = file.getOriginalFilename();

        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String fileName = date + name + "." + type;

        File targetFile = new File(path, fileName);

        try {
            file.transferTo(targetFile);
            return Result.ok("http://localhost:8888/upload/" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }


}
